/**
 * 
 */
package com.marchant.lyh.actions;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.ljw.store.entity.ItemType;
import com.ljw.store.entity.Store;
import com.ljw.store.services.AdminService;
import com.marchant.lyh.domain.Item;

import com.marchant.lyh.services.ItemService;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

/**
 * @author Administrator
 * 
 */
public class itemAction extends ActionSupport {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Item item;
	private int pageSize;
	private int pageNumber;
	private int totalPage;

	private static int BUFFER_SIZE = 16 * 1024;
	private File itemPicture;
	private String itemPictureContentType;
	private String itemPictureFileName;
	private Object imageFileName;

	@Resource
	private ItemService itemService;
	private List<Item> allItem;
	String itemType;
	int itemTypeNum;
	@Resource
	private AdminService adminService;
	private List<ItemType> allItemType;
	
	// 展示餐饮

	public String showItem() {
		// 清缓存
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setHeader("Pragma", "no-cache");
		response.setDateHeader("Expires", 0);
		response.addHeader("Cache-Control", "no-cache");
		response.addHeader("Cache-Control", "no-store");
		response.addHeader("Cache-Control", "must-revalidate");

		HttpServletRequest request = ServletActionContext.getRequest();
		String pageNumberStr = request.getParameter("pageNumber");

		HttpSession session = request.getSession();
		Store store = new Store();
		store = (Store) session.getAttribute("loginstore");
		if (store == null) {
			return Action.INPUT;
		}

		if (pageNumberStr == null || "".equals(pageNumberStr.trim())) {
			pageNumberStr = "1";
		}
		pageSize = 8;
		int itemAmount = itemService.itemAmount(store);

		/*
		 * itemAmount:记录数据库中的item数目 pageSize：规定一页显示的item数目
		 * pageNumberStre：你所要前往的页面页号
		 */

		int[] paging = new int[2];
		System.out.println(paging);

		paging = itemService.pageNumber(itemAmount, pageNumberStr, pageSize);
		pageNumber = paging[0];
		totalPage = paging[1];

		/*
		 * pageNumber方法返回的paging[] paging[0]：你所要前往的正确页面页号 paging[1]：总共的页数
		 * 
		 * pageNumber在jsp页面出现两种特殊情况 ① 、如果在第一页，点击上一页，pageNumber=0 ②、如果在最后一页，点击下一页
		 * pageNumber=totalPage+1 所以pageNumber 在①、pageNumber=1
		 * 在②、pageNumber=totalPage
		 */

		try {
			/* List<Item> itemListTemp = new ArrayList<Item>(); */
			allItem = itemService.searchAllItem(store, pageNumber, pageSize);

			/*
			 * for (Item itemTemp : itemListTemp) { if
			 * (itemTemp.getItemType().equals("a")) itemTemp.setItemType("主食");
			 * else if (itemTemp.getItemType().equals("b"))
			 * itemTemp.setItemType("小吃"); else if
			 * (itemTemp.getItemType().equals("c")) itemTemp.setItemType("面食");
			 * allItem.add(itemTemp); }
			 */

		} catch (Exception ex) {
			ex.printStackTrace();
			return Action.INPUT;
		} finally {

		}

		/*
		 * for (Item showItem : allItem) {
		 * 
		 * System.out.println("名字" + showItem.getItemName());
		 * 
		 * }
		 */

		return Action.SUCCESS;

	}

	public String showItemOfType() {
		// 清缓存
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setHeader("Pragma", "no-cache");
		response.setDateHeader("Expires", 0);
		response.addHeader("Cache-Control", "no-cache");
		response.addHeader("Cache-Control", "no-store");
		response.addHeader("Cache-Control", "must-revalidate");

		HttpServletRequest request = ServletActionContext.getRequest();
		String pageNumberStr = request.getParameter("pageNumberr");

		itemType = request.getParameter("itemType");
		

		HttpSession session = request.getSession();
		Store store = new Store();
		store = (Store) session.getAttribute("loginstore");
		if (store == null) {
			return Action.INPUT;
		}

		if (pageNumberStr == null || "".equals(pageNumberStr.trim())) {
			pageNumberStr = "1";
		}
		pageSize = 8;
		int itemAmount = itemService.itemAmount(store, itemType);

		int[] paging = new int[2];
		System.out.println(paging);

		paging = itemService.pageNumber(itemAmount, pageNumberStr, pageSize);
		pageNumber = paging[0];
		totalPage = paging[1];

		try {

			allItem = itemService.searchItem(store, pageNumber, pageSize,
					itemType);

			if (itemType.equals("主食"))
				itemTypeNum = 1;
			else if (itemType.equals("小吃"))
				itemTypeNum = 2;
			else if (itemType.equals("面食"))
				itemTypeNum = 3;

			System.out.println("====");
			System.out.println(itemTypeNum);
			System.out.println("====");

		} catch (Exception ex) {
			ex.printStackTrace();
			return Action.INPUT;
		} finally {

		}

		return Action.SUCCESS;

	}

	// 删除餐饮

	public String deleteItem()  {
		HttpServletRequest request = ServletActionContext.getRequest();
		Integer itemId = Integer.parseInt(request.getParameter("id"));
		Item item = new Item();
		item.setItemId(itemId);
		

		HttpSession session = request.getSession();
		Store store = new Store();
		store = (Store) session.getAttribute("loginstore");
		item.setStore(store);

		if (store == null) {
			return "emptyUser";
		}
		
		try {
            
			List<Item> listTemp = itemService.searchItem(item);
			for (Item itemTemp2 : listTemp) {
				item = itemTemp2;
			}

			final String path = ServletActionContext.getServletContext()
					.getRealPath("/marchantview/itemImage");

			File imageFile = new File(path
					+ "/"
					+ item.getItemPicture().replace(
							"marchantview/itemImage/", ""));
	        if(imageFile.isFile() && imageFile.exists())
	        	imageFile.delete();
	        
	        itemService.deleteItemHQL("delete from Cart where itemId= '"+item.getItemId()+"'");
			itemService.deleteItem(item);

		} catch (Exception ex) {
			ex.printStackTrace();
			return Action.INPUT;
		} finally {
		}
		return Action.SUCCESS;
	}

	// 插入新餐饮

	private static void copy(File src, File dst) {
		try {
			InputStream in = null;
			OutputStream out = null;
			try {
				in = new BufferedInputStream(new FileInputStream(src));
				out = new BufferedOutputStream(new FileOutputStream(dst));
				byte[] buffer = new byte[BUFFER_SIZE];

				while (in.read(buffer) > 0) {
					out.write(buffer);
				}

			} finally {
				if (null != in) {
					in.close();
				}
				if (null != out) {
					out.close();
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static String getExtention(String fileName) {
		int pos = fileName.lastIndexOf(".");
		return fileName.substring(pos);

	}

	public String addItem()  {
		// TODO Auto-generated method stub
		// File itemPicture【从表单得到的值】

		// 设置下面copy目标文件的文件名
		imageFileName = new Date().getTime()
				+ getExtention(itemPictureFileName);

		// 设置下面copy目标文件的路径
		final String path = ServletActionContext.getServletContext()
				.getRealPath("/marchantview/itemImage");

		// 创建文件目录
		File dir = new File(path);
		if (!dir.exists())
			dir.mkdirs();

		// 将上面设置好的文件名以及目录赋值
		File imageFile = new File(path + "/" + imageFileName);

		// 将itemPicture文件copy到imageFile
		copy(itemPicture, imageFile);

		item.setItemPicture("marchantview/itemImage" + "/" + imageFileName);

		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();

		Store store = new Store();
		store = (Store) session.getAttribute("loginstore");
		
		
		
		if (store == null) {
			return "emptyUser";
		}
		
		String itemTypename = itemService.searchType(item.getItemType());
		item.setItemTypename(itemTypename);
		item.setStore(store);
		
		try {
			itemService.insertItem(item);
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
		}
		return Action.SUCCESS;

	}

	// 修改餐饮

	public String itemTransfer()  {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		//把用到的修改餐饮放session (id)
		String id= request.getParameter("id");
		if(id == null)
		{
			id=(String)session.getAttribute("id");
		}
		if(session.getAttribute("id") != null){
			session.removeAttribute("id");
		}
		session.setAttribute("id", id);
		
		Integer itemId = Integer.parseInt(id);
		Item itemTemp = new Item();

		
		Store store = new Store();
		store = (Store) session.getAttribute("loginstore");

		if (store == null) {
			return "emptyUser";
		}
		
		allItemType = adminService.alltype();
		
		itemTemp.setItemId(itemId);
		try {
			List<Item> listTemp = itemService.searchItem(itemTemp);

			for (Item itemTemp2 : listTemp) {
				item = itemTemp2;
			}

		} catch (Exception ex) {
			ex.printStackTrace();
			return Action.INPUT;
		} finally {
		}

		return Action.SUCCESS;
	}

	public String editItem()  {

		HttpServletResponse response = ServletActionContext.getResponse();
		response.setHeader("Pragma", "no-cache");
		response.setDateHeader("Expires", 0);
		response.addHeader("Cache-Control", "no-cache");
		response.addHeader("Cache-Control", "no-store");
		response.addHeader("Cache-Control", "must-revalidate");
		
		item.setItemDescription(item.getItemDescription().trim());
		Item itemTemp = new Item();
		
		List<Item> listTemp = itemService.searchItem(item);
		for (Item itemTemp2 : listTemp) {
			itemTemp = itemTemp2;
		}

		final String path = ServletActionContext.getServletContext()
				.getRealPath("/marchantview/itemImage");

		File imageFile = new File(path
				+ "/"
				+ itemTemp.getItemPicture().replace("marchantview/itemImage/",
						""));
		if (itemPicture != null)
			copy(itemPicture, imageFile);

		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		Store store = new Store();
		store = (Store) session.getAttribute("loginstore");
		item.setStore(store);

		if (store == null) {
			return "emptyUser";
		}
		String itemTypename = itemService.searchType(item.getItemType());
		item.setItemTypename(itemTypename);
		item.setItemPicture(itemTemp.getItemPicture());

		try {
			itemService.updateItem(item);
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
		}
		return Action.SUCCESS;
	}




	//(关伟君)
	//展示热门餐饮
	public String showhotItem() {
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setHeader( "Pragma", "no-cache" );  
		response.setDateHeader("Expires", 0);  
		response.addHeader( "Cache-Control", "no-cache" );  
		response.addHeader( "Cache-Control", "no-store" );  
		response.addHeader( "Cache-Control", "must-revalidate" );	
		HttpServletRequest request = ServletActionContext.getRequest();
		String pageNumberStr = request.getParameter("pageNumber");			       
		if (pageNumberStr == null || "".equals(pageNumberStr.trim())) {
			pageNumberStr = "1";
		}
		pageSize = 8;
		int itemAmount = itemService.itemAmount();
		int[] paging = new int[2];
		System.out.println(paging);

		paging = itemService.pageNumber(itemAmount, pageNumberStr, pageSize);
		pageNumber = paging[0];
		totalPage = paging[1];
		
		
		try {
			allItem = itemService.searchhotAllItem( pageNumber, pageSize);
		} catch (Exception ex) {
			ex.printStackTrace();
			return Action.INPUT;
		} finally {
		}
		return Action.SUCCESS;
	}
	//展示分类商品
	public String showspItem() {
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setHeader( "Pragma", "no-cache" );  
		response.setDateHeader("Expires", 0);  
		response.addHeader( "Cache-Control", "no-cache" );  
		response.addHeader( "Cache-Control", "no-store" );  
		response.addHeader( "Cache-Control", "must-revalidate" );	
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		String pageNumberStr = request.getParameter("pageNumber");			       
		if (pageNumberStr == null || "".equals(pageNumberStr.trim())) {
			pageNumberStr = "1";
		}
		pageSize = 8;
		
		String sp= request.getParameter("sp");
		if(sp==null)
		{
			sp=(String)session.getAttribute("sp");
		}
		if(session.getAttribute("sp") != null){
			session.removeAttribute("sp");
		}
		session.setAttribute("sp", sp);
		//分类
		if(sp.equals("a"))
			sp="主食";
		if(sp.equals("b"))
			sp="小吃";
		if(sp.equals("c"))
			sp="面食";
		int itemAmount = itemService.itemspAmount(sp);
		int[] paging = new int[2];
		System.out.println(paging);
		paging = itemService.pageNumber(itemAmount, pageNumberStr, pageSize);
		pageNumber = paging[0];
		totalPage = paging[1];	
		try {
			allItem = itemService.searchspAllItem(sp , pageNumber, pageSize);
		} catch (Exception ex) {
			ex.printStackTrace();
			return Action.INPUT;
		} finally {
		}
		return Action.SUCCESS;
	}
	//展示商店餐饮
	public String showshopItem() {
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setHeader( "Pragma", "no-cache" );  
		response.setDateHeader("Expires", 0);  
		response.addHeader( "Cache-Control", "no-cache" );  
		response.addHeader( "Cache-Control", "no-store" );  
		response.addHeader( "Cache-Control", "must-revalidate" );	
		HttpServletRequest request = ServletActionContext.getRequest();
		String pageNumberStr = request.getParameter("pageNumber");			       
		if (pageNumberStr == null || "".equals(pageNumberStr.trim())) {
			pageNumberStr = "1";
		}
		pageSize = 8;
		HttpSession session = request.getSession();
		String shopId= request.getParameter("shopId");
		if(shopId==null)
		{
			shopId=(String)session.getAttribute("shopIdtemp");
		}
		if(session.getAttribute("shopIdtemp") != null){
			session.removeAttribute("shopIdtemp");
		}
		session.setAttribute("shopIdtemp", shopId);
		int itemAmount = itemService.itemshopAmount(shopId);
		int[] paging = new int[2];
		System.out.println(paging);

		paging = itemService.pageNumber(itemAmount, pageNumberStr, pageSize);
		pageNumber = paging[0];
		totalPage = paging[1];
		
		
		try {
			allItem = itemService.searchshopAllItem(shopId, pageNumber, pageSize);
		} catch (Exception ex) {
			ex.printStackTrace();
			return Action.INPUT;
		} finally {
		}
		return Action.SUCCESS;
	}
	
	// 校验器
	public void validateAddItem() {

		/*
		 * System.out.println("****");
		 * System.out.println(this.item.getItemName() == null ||
		 * "".equals(this.item.getItemName().trim()));
		 * System.out.println("****");
		 */

		if (this.item.getItemName() == null
				|| "".equals(this.item.getItemName().trim())) {
			// 添加错误信息
			this.addFieldError("itemName", "餐饮名不能为空");
		}

		if (this.item.getItemPrice() == null) {
			// 添加错误信息
			this.addFieldError("itemPrice", "价格填写错误");
		}

		if (this.itemPicture == null) {
			this.addFieldError("itemPicture", "图片不能为空");
		}

		if (this.item.getItemNum() == null || this.item.getItemNum() < 0) {
			this.addFieldError("itemNum", "餐饮销量填写错误");
		}

	}

	public void validateEditItem() {

		if (this.item.getItemName() == null
				|| "".equals(this.item.getItemName().trim())) {
			// 添加错误信息
			this.addFieldError("itemName", "餐饮名不能为空");
		}

		if (this.item.getItemPrice() == null) {
			// 添加错误信息
			this.addFieldError("itemPrice", "价格填写错误");
		}

		if (this.item.getItemNum() == null || this.item.getItemNum() < 0) {
			this.addFieldError("itemNum", "餐饮销量填写错误");
		}

	}
	 

	//------------------------------------------------------------------

	public Item getItem() {
		return item;
	}

	public String getItemType() {
		return itemType;
	}

	public void setItemType(String itemType) {
		this.itemType = itemType;
	}

	public int getItemTypeNum() {
		return itemTypeNum;
	}

	public void setItemTypeNum(int itemTypeNum) {
		this.itemTypeNum = itemTypeNum;
	}

	public void setItem(Item item) {
		this.item = item;
	}

	public ItemService getItemService() {
		return itemService;
	}

	public void setItemService(ItemService itemService) {
		this.itemService = itemService;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getPageNumber() {
		return pageNumber;
	}

	public void setPageNumber(int pageNumber) {
		this.pageNumber = pageNumber;
	}

	public int getTotalPage() {
		return totalPage;
	}

	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}

	public void setAllItem(List<Item> allItem) {
		this.allItem = allItem;
	}

	public List<Item> getAllItem() {
		return allItem;
	}

	public File getItemPicture() {
		return itemPicture;
	}

	public void setItemPicture(File itemPicture) {
		this.itemPicture = itemPicture;
	}

	public String getItemPictureContentType() {
		return itemPictureContentType;
	}

	public void setItemPictureContentType(String itemPictureContentType) {
		this.itemPictureContentType = itemPictureContentType;
	}

	public String getItemPictureFileName() {
		return itemPictureFileName;
	}

	public void setItemPictureFileName(String itemPictureFileName) {
		this.itemPictureFileName = itemPictureFileName;
	}

	public Object getImageFileName() {
		return imageFileName;
	}

	public void setImageFileName(Object imageFileName) {
		this.imageFileName = imageFileName;
	}

	public List<ItemType> getAllItemType() {
		return allItemType;
	}

	public void setAllItemType(List<ItemType> allItemType) {
		this.allItemType = allItemType;
	}
	
}
